package cn.conac.rc.itm.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.itm.entity.DelItemAppEntity;
import cn.conac.rc.itm.repository.DelItemAppRepository;
import cn.conac.rc.itm.vo.DelItemVo;

@Service
public class DelItemAppService extends GenericService<DelItemAppEntity, Integer> {

	@Autowired
	private DelItemAppRepository repository;

	/**
	 * 计数查询
	 *
	 * @param vo
	 * @return 计数结果
	 */
	public long count(DelItemVo vo) {
		return super.count(this.createCriteria(vo));
	}

	/**
	 * 动态查询，分页，排序查询
	 *
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<DelItemAppEntity> findItemsByOrgId(DelItemVo vo) throws Exception {
		try {
			Sort sort = new Sort(Sort.Direction.ASC, "id");
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<DelItemAppEntity> dc = this.createCriteria(vo);
			return repository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 *
	 * @param vo
	 * @return Criteria
	 */
	private Criteria<DelItemAppEntity> createCriteria(DelItemVo vo) {
		Criteria<DelItemAppEntity> dc = new Criteria<>();
		// 机构ID
		if (StringUtils.isNotBlank(vo.getOrgId())) {
			dc.add(Restrictions.eq("orgId", vo.getOrgId(), true));
		}
		// 责任事项名称
		if (StringUtils.isNotBlank(vo.getDutyContent())) {
			dc.add(Restrictions.like("dutyContent", vo.getDutyContent(), true));
		}
		// 对应地区ID
		if (StringUtils.isNotBlank(vo.getAreaId())) {
			dc.add(Restrictions.eq("areaId", vo.getAreaId(), true));
		}
		return dc;
	}
	
	/**
	 * 获取权力对应的责任处室
	 *
	 * @param itemId
	 * @return List<String>
	 */
	public String findDeptNames(Integer itemId) {
		String deptNames = "";
		List<String> deptNameList = repository.findDeptNames(itemId);
		if(null != deptNameList && deptNameList.size() > 0){
			for(String deptName : deptNameList){
				if(deptNames != ""){
					deptNames = deptNames + ",";
				}
				deptNames = deptNames + deptName;
			}
		}
		return deptNames;
	}

	/**
	 * 通过权力Id获取对应的责任信息列表
	 * @param itemsInfoId
	 * @return List<DelItemAppEntity>
	 */
	public List<DelItemAppEntity> findDelInfoByItemsInfoId(Integer itemsInfoId){
		List<String> operations = new ArrayList<>();
		operations.add("A");
		operations.add("C");
		return repository.findByItemsInfoIdAndOperationInOrderById(itemsInfoId,operations);
	}
}
